import { window, commands, ExtensionContext, Range } from 'vscode'
import type { Selection, TextEditor } from 'vscode'
import { showErrorMessage } from '../showErrorMessage'
import { insertText } from '../insertText'
import { generateCodeByAst } from './plugins/auth'

const { activeTextEditor, onDidChangeActiveTextEditor } = window
let currentEditor: TextEditor | undefined

export const installPlugin = (context: ExtensionContext) => {
  currentEditor = activeTextEditor

  onDidChangeActiveTextEditor((editor) => (currentEditor = editor))
  commands.registerTextEditorCommand('bossauto.auth', () => handle(context))
}

// 从vscode中获取当前选中的字段
const getSelectedCodeFromVsCode = () => {
  const editor = window.activeTextEditor

  if (!editor) {
    return showErrorMessage()
  }

  const { selection } = editor
  return getSelectedCodeFromSelection(selection)
}

const getSelectedCodeFromSelection = (selection: Selection) => {
  /**
   * 判断当前是否有选中的内容
   * 1. 有内容就直接使用
   * 2. 没有就或者当前的一整行
   */
  return selection.isEmpty
    ? getWholeLineCode(currentEditor)
    : currentEditor?.document.getText(selection)
}

const getWholeLineCode: (currentEditor?: TextEditor) => string = (currentEditor?: TextEditor) => {
  if (currentEditor) {
    const { document, selection } = currentEditor
    const { start } = selection
    const wholeLineText = document.lineAt(start)

    return wholeLineText.text
  }

  return ''
}

const handle = (context: ExtensionContext) => {
  let selectedCode = getSelectedCodeFromVsCode()
  let { code } = generateCodeByAst(selectedCode || '')

  insertText(code)
}
